/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <div class="table-data">
        <sf-grid>
            <sf-toolbar ref="toolbar">
                <sf-button
                    ref="submit"
                    class="creat-button btn-blank"
                    icon-cls="iconrefresh"
                    @click="_refresh">
                    <lang>刷新</lang>
                </sf-button>
            </sf-toolbar>
            <sf-table 
                ref="updateTimeTable" 
                :options="options_fix"
                @pagechange="_onPageChange"
                @sizechange="_onSizeChange">
                <sf-table-column :default-width="20"
                                 type="index">
                    <lang>序号</lang>
                </sf-table-column>
                <sf-table-column data-index="createTime"
                                 :default-width="40">
                    <lang>开始时间</lang>
                </sf-table-column>
                <sf-table-column data-index="name"
                                 :default-width="40">
                    <lang>任务名称</lang>
                </sf-table-column>
                <sf-table-column data-index="flowName"
                                 :default-width="30">
                    <lang>AI FLOW</lang>
                </sf-table-column>
                <sf-table-column data-index="status"
                                 :default-width="30">
                    <lang>状态</lang>
                </sf-table-column>
                <sf-table-column data-index="parameters"
                                 :default-width="50">
                    <lang>参数</lang>
                </sf-table-column>
                <sf-table-column data-index="metrics"
                                 :default-width="60">
                    <lang>指标</lang>
                </sf-table-column>
                <sf-table-column data-index="opr"
                                 :default-width="80">
                    <lang>操作</lang>
                </sf-table-column>
                <template slot="createTime"
                          slot-scope="{record}">
                    {{ encodeTime(record.createTime) }}
                </template>
                <template slot="status"
                          slot-scope="{record}">
                    <div class="task-flex"
                         :class="repositoryStatusClass(record.status)">
                        <span class="status-img task-common"></span>
                        <span class="status-text">{{ repositoryStatusText(record.status) }}</span>
                    </div>
                </template>
                <template slot="parameters"
                          slot-scope="{record}">
                    <div v-if="!record.parameters">
                        -
                    </div>
                    <div v-else>
                        <div v-for="(item,index) in record.parameters.slice(0,2)"
                             :key="index"
                             :title="translateParams(item.name,item.value)"
                             class="m-tb5">
                            {{ item.name }} : <span class="font-weight">{{ item.value }}</span>
                        </div>
                    </div>
                </template>
                <template slot="metrics"
                          slot-scope="{record}">
                    <div v-if="!record.metrics">
                        -
                    </div>
                    <div v-else
                         class="metrics-flex">
                        <div v-for="(item,index) in record.metrics"
                             :key="index"
                             :title="translateParams(item.name,item.number_value)"
                             class="metrics-name">
                            {{ item.name }} : <span class="font-weight">{{ item.number_value }}</span>
                        </div>
                    </div>
                </template>
                <template slot="createTime"
                          slot-scope="{record}">
                    {{ encodeTime(record.createTime) }}
                </template>
                <template slot="opr"
                          slot-scope="{record}">
                    <div class="opr">
                        <a 
                            class="link-btn"
                            @click="_enterTaskDetail(record)">
                            <lang>查看详情</lang>
                        </a>
                        <a 
                            class="link-btn"
                            @click="_deleteInteractTask(record)">
                            <lang>删除</lang>
                        </a>
                    </div>
                </template>
            </sf-table>
        </sf-grid>
    </div>
</template>
<script>
import {encodeDate} from '@sxf/sf-vue-component/src/util/format';

// import parseJson from 'src/util/parse_json.ts';
import trainingUrlAdapter from 'src/home/mod_common/training_url_adapter';

import { setStorage } from 'src/util/local_storage';


/* 训练状态 */
const PAGE_COUNT = 10;

const REPOSITORY_STATUS_TEXT = {
    0:_('任务完成'),
    1:_('任务中'),
    2:_('任务失败'),
    3:_('任务异常'),
    4:_('任务终止'),
    5:_('任务创建中')
};
const REPOSITORY_STATUS_CLASS = {
    0:'task-success',
    1:'task-run',
    2:'task-fail',
    3:'task-fail',
    4:'task-fail',
    5:'task-run'
};

export default {
    name: 'PeriodChildTask',
    props:{
        taskId:{
            type:String,
            default:''
        }
    },
    data () {
        return {
            searchParams: {
                pageSize: PAGE_COUNT,
                pageNum: 1,
            },
            defaultWidth:200,
            intervalTask:null,
            showEmptytraining:false,
            emptyText:_('没有找到对应的模型'),
            options_fix: {
                bufferView: false,

                // 配置这个后才可以实现保持勾选状态
                idProperty: 'id',
                selectionHide: true,
                autoHeight:true,
                pagination: {
                    activePage: 1,
                    pageSize: PAGE_COUNT,
                    pageSizes: [Number('10'), Number('20'), Number('50')],
                    layout: [ 'pager', 'sizes', 'jumper']
                }
            },
            flowList:[],
            flowId:''
        };
    },
    computed: {
        projectId () {
            return this.$route.query.projectId || '';
        }

    },
    watch: {
        taskId () {
             this.refreshGrid();
        }
    },
    methods: {
        repositoryStatusClass (status) {
            return REPOSITORY_STATUS_CLASS[status];
        },
        repositoryStatusText (status) {
            return REPOSITORY_STATUS_TEXT[status];
        },

        // 刷新grid
        async refreshGrid () {
            this.$mask();
            const TRAINING_GET_URL = trainingUrlAdapter(`interactiveTask/job/${this.taskId}/run`);
            this.$unmask();
            let jsonData = await this.$ajax.get(TRAINING_GET_URL, this.searchParams);
            let table = this.$refs.updateTimeTable;
            let {success, msg, data} = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                table.loadData([]);
                return;
            }
            if (!table) {
                return;
            }
            this.showEmptytraining = data.list.length === 0;
            table.loadData(data.list || []);
            table.getPagination().setTotal(data.total);
        },

        encodeTime (time) {
            return encodeDate(time);
        },
        async ajaxDeleteInteractTask (record) {
            const DELETE_URL = trainingUrlAdapter(`interactiveTask/job/${record.id}/run`);
            this.$mask();
            let jsonData = await this.$ajax.delete(DELETE_URL);
            this.$unmask();
            let {success, msg} = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                return;
            }
            this.$ok(_('删除成功'));
            this.refreshGrid();
        },
        _deleteInteractTask (record) {
            this.$confirm({
                title: _('提示'),
                subTitle: _('确定要删除{0}任务吗？', record.name),
                msg: _('删除后，操作无法撤回，请谨慎操作！'),
                icon: 'warning',
                autoClose: true,
                callback: actionName => {
                    if (actionName === 'submit') {
                        this.ajaxDeleteInteractTask(record);
                    }
                }
            });
        },
        _onPageChange (pageNum) {
            Object.assign(this.searchParams, {
                pageNum: pageNum
            });
            this.refreshGrid();
        },
        _onSizeChange (nowPageIndex, nowPageSize) {
            Object.assign(this.searchParams, {
                pageNum: nowPageIndex,
                pageSize: nowPageSize
            });
            this.refreshGrid();
        },
        _refresh () {
            this.refreshGrid();
        },
        translateParams (name, value) {
            return `${name} : ${value}`;
        },
        _enterTaskDetail (item) {
            setStorage('taskInfo', JSON.stringify(item));

            // 跳到周期任务
            setStorage('interactType', 1);
            this.$router.push({
                path: `/project_manager/interact_task_detail`,
                query: Object.assign(this.$route.query, {taskName:item.name})
            });
        }
    },
    beforeDestroy () {
        if (this.intervalTask) {
            this.intervalTask.stop();
            this.intervalTask = null;
        }
    }
};
</script>
<style lang="less">
    .metrics-flex{
        display: flex;
        flex-wrap: wrap;
        .metrics-name{
            margin: 5px 10px;
        }
    }
</style>
